package com.epam.cdp.ejb.stateless.jms;

import javax.annotation.Resource;
import javax.ejb.Stateless;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

@Stateless
public class JMSQueueClient implements MessageSender<String> {
	private final static Log log = LogFactory.getLog(JMSQueueClient.class);
	
	@Resource(mappedName = JMSResourcePropertyStore.FACTORY_NAME)
	private ConnectionFactory connectionFactory;

	@Resource(mappedName = JMSResourcePropertyStore.QUEUE_NAME)
	private Queue queue;

	public ConnectionFactory getConnectionFactory() {
		return connectionFactory;
	}

	public void setConnectionFactory(ConnectionFactory connectionFactory) {
		this.connectionFactory = connectionFactory;
	}

	public Queue getQueue() {
		return queue;
	}

	public void setQueue(Queue queue) {
		this.queue = queue;
	}

	@Override
	public void sendMessage(String message) {
		log.info("Trying to send message " + message + " to queue " + JMSResourcePropertyStore.QUEUE_NAME);
		Connection connection = null;
		Session session = null;
		try {
			connection = connectionFactory.createConnection();
			session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
			MessageProducer messageProducer = session.createProducer(queue);
			
			TextMessage textMessage = session.createTextMessage();
			textMessage.setText(message);
			messageProducer.send(textMessage);
			log.info("Message " + message + " was successfully sent.");
		} catch (JMSException e) {
			log.error("Can't sent message " + message + " to JMSQueue " + JMSResourcePropertyStore.QUEUE_NAME , e);
		} finally {
			closeSession(session);
			closeConnection(connection);
		}

	}

	private void closeSession(Session session) {
		if (session != null) {
			try {
				session.close();
			} catch (JMSException e) {
				log.error("Failed to close session");
			}
		}
	}

	private void closeConnection(Connection connection) {
		if (connection != null) {
			try {
				connection.close();
			} catch (JMSException e) {
				log.error("Failed to close connection");
			}
		}
	}
	
}
